<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    title="新增退货"
    width="1200px"
    @close="handleClose"
  >
    <!-- 第一步：选择产品 -->
    <div v-if="currentStep === 0" class="step-content">
      <el-form
        ref="step1FormRef"
        :model="step1Form"
        :rules="step1Rules"
        class="step-form"
      >
        <el-descriptions :column="1" border class="custom-descriptions">
          <el-descriptions-item label="*合同类型">
            <el-form-item prop="contractType" style="margin-top: 11px;">
              <el-select
                v-model="step1Form.contractType"
                placeholder="请选择"
                style="width: 100%;"
                @change="handleContractTypeChange"
              >
                <el-option label="工程类" value="engineering" />
                <el-option label="直销类" value="directSale" />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*合同名称">
            <el-form-item prop="contractName" style="margin-top: 11px;">
              <el-select
                v-model="step1Form.contractName"
                placeholder="请选择"
                style="width: 100%;"
                @change="handleContractNameChange"
              >
                <el-option v-for="item in contractNameOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*物料类型">
            <el-form-item prop="materialType" style="margin-top: 11px;">
              <!-- 将普通el-select改为el-tree-select -->
              <el-tree-select
                v-model="step1Form.materialType"
                :data="materialTreeData"
                placeholder="请选择"
                :props="treeSelectProps"
                filterable
                allow-clear
                show-checkbox
                check-strictly
                style="width: 100%;"
              />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*关联需求/生产加工单">
            <el-form-item prop="relatedRequirements" style="margin-top: 11px;">
              <!-- 将普通el-select改为el-cascader -->
              <el-cascader
                v-model="step1Form.relatedRequirements"
                :options="requirementOptions"
                :props="cascaderProps"
                placeholder="可选任意多个已出库的需求下的多个生产加工单"
                style="width: 100%;"
              />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="可退货列表" :rowspan="6">
            <!-- 可退货列表 -->
            <div class="product-list-section">
              <el-table :data="returnableList" style="width: 100%" border>
                <el-table-column type="selection" align="left" />
                <el-table-column prop="productNo" label="产品编号" align="left" />
                <el-table-column prop="materialContent" label="物料内容" align="left" />
                <el-table-column prop="relatedRequirement" label="关联需求" align="left" sortable />
                <el-table-column prop="productionOrder" label="生产加工单" align="left" sortable />
                <el-table-column label="操作" align="left" width="100">
                  <template #default="scope">
                    <el-link type="primary" @click="handleViewParams(scope.row)">查看参数</el-link>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页 -->
              <div style="margin-top: 10px;">
                <pagination
                  :total="returnableList.length"
                />
              </div>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
    </div>

    <!-- 第二步：填写信息 -->
    <div v-if="currentStep === 1" class="step-content">
      <el-form
        ref="step2FormRef"
        :model="step2Form"
        :rules="step2Rules"
        class="step-form"
      >
        <el-descriptions :column="1" border class="custom-descriptions">
          <el-descriptions-item label="客户名称">
            <el-form-item style="margin-top: 11px;">
              <el-input v-model="step2Form.customerName" placeholder="客户名称" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="物料类型">
            <el-form-item style="margin-top: 11px;">
              <el-input v-model="step2Form.materialType" placeholder="物料类型" style="width: 100%;" :disabled="true" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*退货地址">
            <el-form-item prop="returnAddress" style="margin-top: 11px;">
              <el-input v-model="step2Form.returnAddress" placeholder="本公司的收货地址" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*退货联系人">
            <el-form-item prop="returnContact" style="margin-top: 11px;">
              <el-input v-model="step2Form.returnContact" placeholder="本公司的收货联系人" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*退货联系方式">
            <el-form-item prop="returnPhone" style="margin-top: 11px;">
              <el-input v-model="step2Form.returnPhone" placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*退货物流单号">
            <el-form-item prop="logisticsNo" style="margin-top: 11px;">
              <el-input v-model="step2Form.logisticsNo" placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
          
          <el-descriptions-item label="*退货原因">
            <el-form-item prop="returnReason" style="margin-top: 11px;">
              <el-input v-model="step2Form.returnReason" placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-descriptions-item>
        </el-descriptions>
      </el-form>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <template v-if="currentStep === 1">
          <el-button @click="goToPrevStep">上一步</el-button>
          <el-button type="primary" @click="handleComplete">完成</el-button>
        </template>
        <template v-else-if="currentStep === 0">
          <el-button type="primary" @click="goToNextStep">下一步</el-button>
        </template>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineEmits, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  materialTreeData: {
    type: Array,
    default: () => []
  },
  contractNameOptions: {
    type: Array,
    default: () => []
  },
  requirementOptions: {
    type: Array,
    default: () => []
  }
})

// 定义emits
const emit = defineEmits(['close', 'complete', 'update:visible'])

// 当前步骤
const currentStep = ref(0)

// 表单引用
const step1FormRef = ref(null)
const step2FormRef = ref(null)

// 第一步表单数据
const step1Form = reactive({
  contractType: '',
  contractName: '',
  materialType: '', // 改为字符串类型
  relatedRequirements: [] // 用于级联选择器的数组类型
})

// 第二步表单数据
const step2Form = reactive({
  customerName: '',
  materialType: '',
  returnAddress: '',
  returnContact: '',
  returnPhone: '',
  logisticsNo: '',
  returnReason: ''
})
// 树形选择配置
const treeSelectProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}

// 级联选择器配置
const cascaderProps = {
  multiple: true, // 开启多选模式
  expandTrigger: 'click', // 点击展开子菜单
  collapseTags: true, // 折叠标签
  collapseTagsTooltip: true, // 鼠标悬停折叠文字时显示具体所选值
  label: 'label',
  value: 'value',
  children: 'children'
}
// 第一步表单校验规则
const step1Rules = {
  contractType: [
    { required: true, message: '请选择合同类型', trigger: 'change' }
  ],
  contractName: [
    { required: true, message: '请选择合同名称', trigger: 'change' }
  ],
  materialType: [
    { required: true, message: '请选择物料类型', trigger: 'change' } // 移除type和min
  ],
  relatedRequirements: [
    { 
      required: true, 
      type: 'array',
      min: 1,
      message: '请选择关联需求/生产加工单', 
      trigger: 'change'
    }
  ]
}

// 第二步表单校验规则
const step2Rules = {
  returnAddress: [
    { required: true, message: '请输入退货地址', trigger: 'blur' }
  ],
  returnContact: [
    { required: true, message: '请输入退货联系人', trigger: 'blur' }
  ],
  returnPhone: [
    { required: true, message: '请输入退货联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  logisticsNo: [
    { required: true, message: '请输入退货物流单号', trigger: 'blur' }
  ],
  returnReason: [
    { required: true, message: '请输入退货原因', trigger: 'blur' }
  ]
}

// 模拟可退货列表数据
const returnableList = ref([
  {
    productNo: 'CPBH001',
    materialContent: '防火门/二级分类/木质门框',
    relatedRequirement: '需求1',
    productionOrder: 'SCJHDD001'
  },
  {
    productNo: 'CPBH002',
    materialContent: '防火门/二级分类/木质门框',
    relatedRequirement: '需求1',
    productionOrder: 'SCJHDD001'
  },
  {
    productNo: 'CPBH003',
    materialContent: '防火门/二级分类/木质门扇',
    relatedRequirement: '需求2',
    productionOrder: 'SCJHDD004'
  }
])

// 处理合同类型变化
const handleContractTypeChange = (value) => {
  // 如果选择直销类，直接显示需求名称
  if (value === 'directSale') {
    ElMessage.info('直销类合同直接显示需求名称')
  }
}

// 添加物料类型选择处理函数
const handleMaterialTypeChange = (data, checked, indeterminate) => {
  // 确保只选中一个一级节点
  if (checked) {
    // 清除之前的选中状态，只保留当前选中的一级节点
    const isFirstLevel = !data.parentId
    if (isFirstLevel) {
      // 过滤掉已存在的选中值，只保留新选中的
      step1Form.materialType = [data.value]
    }
  }
}

// 处理合同名称变化
const handleContractNameChange = (value) => {
  // 实际项目中这里可能需要根据合同名称加载相关数据
}

// 查看参数
const handleViewParams = (row) => {
  ElMessage.info(`查看${row.materialContent}的参数`)
}

// 进入下一步时的数据处理
const goToNextStep = async () => {
  try {
    await step1FormRef.value.validate()
    // 将第一步的物料类型传递到第二步，处理数组格式
    const materialTypeValue = step1Form.materialType[0]
    step2Form.materialType = materialTypeValue === 'fireDoor' ? '防火门' : '卷帘门'
    currentStep.value = 1
  } catch (error) {
    ElMessage.error('请完善退货单信息')
  }
}

// 回到上一步
const goToPrevStep = () => {
  currentStep.value = 0
}

// 处理完成
const handleComplete = async () => {
  try {
    await step2FormRef.value.validate()
    
    // 合并所有步骤的表单数据
    const allFormData = {
      ...step1Form,
      ...step2Form,
      returnableList: returnableList.value
    }
    
    emit('complete', allFormData)
    
    // 重置表单
    resetForm()
    emit('update:visible', false)
  } catch (error) {
    ElMessage.error('请完善表单信息')
  }
}

// 处理关闭
const handleClose = () => {
  resetForm()
  emit('update:visible', false)
  emit('close')
}

// 重置表单
const resetForm = () => {
  currentStep.value = 0
  
  // 重置第一步表单
  if (step1FormRef.value) {
    step1FormRef.value.resetFields()
  }
  step1Form.contractType = ''
  step1Form.contractName = ''
  step1Form.materialType = [] // 重置为空数组
  step1Form.relatedRequirements = [] // 重置为空数组
  
  // 重置第二步表单
  if (step2FormRef.value) {
    step2FormRef.value.resetFields()
  }
  step2Form.customerName = ''
  step2Form.materialType = ''
  step2Form.returnAddress = ''
  step2Form.returnContact = ''
  step2Form.returnPhone = ''
  step2Form.logisticsNo = ''
  step2Form.returnReason = ''
}

// 初始化
onMounted(() => {
  // 确保没有默认选中的值
  step1Form.materialType = ''
})
</script>

<style scoped>
.step-content {
  overflow: hidden;
}

.step-form {
  margin-bottom: 20px;
}

.product-list-section {
  margin-top: 20px;
  margin-bottom: 20px;
  position: relative;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 自定义描述列表样式 */
.custom-descriptions {
  width: 100%;
}

.custom-descriptions .el-descriptions__item {
  display: flex;
  border-bottom: 1px solid #EBEEF5;
}

.custom-descriptions .el-descriptions__label {
  width: 120px;
  font-weight: 500;
  color: #606266;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.custom-descriptions .el-descriptions__content {
  flex: 1;
  color: #303133;
  display: flex;
  align-items: center;
}

.custom-descriptions .el-descriptions__row:last-child .el-descriptions__item {
  border-bottom: none;
}

.el-descriptions__cell--label {
  background-color: transparent !important;
}
:deep(.custom-descriptions .el-descriptions__cell) {
  padding: 0px 11px !important;
}
.el-form-item {
  margin-bottom: 11px;
}
</style>
